﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;
using ZhiJiao.Models.Entities;
using ZhiJiao.Models.Entities.Enums;
using ZhiJiao.Service.Abstracts;
using ZhiJiao.Service.Dto;
using ZHIJIAO.Models;

namespace ZHIJIAO.Controllers
{
    public class AccountController : Controller
    {
        private readonly SignInManager<User> _signInManager;
        private readonly UserManager<User> _userManager;
        private readonly IAccountService _accountService;
        private readonly ICurrentUser _currentUser;

        public AccountController(SignInManager<User> signInManager,
                                 IAccountService accountService,
                                 ICurrentUser currentUser)
        {
            _signInManager = signInManager;
            _userManager = _signInManager.UserManager;
            _accountService = accountService;
            _currentUser = currentUser;
        }

        /// <summary>
        /// 登录视图
        /// </summary>
        /// <returns></returns>
        public IActionResult Login()
        {
            return View();
        }

        /// <summary>
        /// 添加账户
        /// </summary>
        [HttpPost("api/account/account-submit")]
        public async Task<IActionResult> AddSubmit([FromBody]AddAccountDto account)
        {
           return Json(await _accountService.AddSubmit(account));
        }

        /// <summary>
        /// 删除用户
        /// </summary>
        [HttpGet("api/account/delete-user")]
        public async Task<IActionResult> DeleteUser(string id)
        {
            return Json(await _accountService.Delete(id));
        }

        /// <summary>
        /// 修改账户
        /// </summary>
        [HttpPost("api/account/edit-submit")]
        public async Task<IActionResult> EditSubmit([FromBody] AddAccountDto account)
        {
            return Json(await _accountService.EditSubmit(account));
        }

        /// <summary>
        /// 登录提交
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost("api/account/login-submit")]
        [AllowAnonymous]// 任何人可访问
        public async Task<IActionResult> SubmitLogin([FromBody] LoginUser loginUser)
        {
            BackJson backJson = new BackJson();
            try
            {
                if (loginUser != null && loginUser.UserName != null && loginUser.Pwd != null)
                {
                    var user = await _userManager.FindByNameAsync(loginUser.UserName);
                    if (user != null)
                    {
                        var result = await _signInManager.PasswordSignInAsync(user,      // 用户对象
                                                                  loginUser.Pwd, // 密码
                                                                  false,     // 浏览器是否存储用户名密码
                                                                  false);    // 如果登录失败是否锁定账户
                        if (result.Succeeded)
                        {
                            backJson.code = 0;
                            backJson.msg = "登录成功";
                        }
                        else if (result.IsLockedOut)
                        {
                            backJson.code = 403;
                            backJson.msg = "账号被锁定";
                        }
                        else if (result.IsNotAllowed)
                        {
                            backJson.code = 401;
                            backJson.msg = "登录被拒绝";
                        }
                        else
                        {
                            backJson.code = 1;
                            backJson.msg = "用户名和密码不匹配";
                        }
                    }
                    else
                    {
                        backJson.code = 404;
                        backJson.msg = "不存在此用户！";
                    }
                }
                else
                {
                    backJson.code = 500;
                    backJson.msg = "请输入正确的用户名和密码！";
                }
            }
            catch (Exception e)
            {
                backJson.code = 500;
                backJson.msg = e.Message;
            }
            return Ok(backJson);
        }

        [Authorize]
        [HttpGet]
        public async Task<IActionResult> Logout()
        {
            await _signInManager.SignOutAsync();
            return RedirectToAction("Login");
        }

        public IActionResult Admin()
        {
            ViewBag.UserType = Convert.ToInt32(_currentUser.User.Type);
            if (_currentUser.User.Type == UserType.Instruction)
            {
                ViewBag.InsId = _currentUser.User.Instruction!.Id;
            }
            else
            {
                ViewBag.InsId = -1;
            }
            return View();
        }

        /// <summary>
        /// 修改密码
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Authorize]
        public IActionResult ChangePwd()
        {
            return View();
        }

        /// <summary>
        /// 机构选项
        /// </summary>
        [HttpGet("api/account/get-ins-options")]
        public IActionResult GetInsOptions()
        {
            return Json(_accountService.GetInsOptions());
        }

        /// <summary>
        /// 角色选项
        /// </summary>
        [HttpGet("api/account/get-role-options")]
        public IActionResult GetRoleOptions(RoleType roleType,long? insId)
        {
            return Json(_accountService.GetRoleOptions(roleType,insId));
        }

        /// <summary>
        /// 查询用户列表
        /// </summary>
        [HttpPost("api/account/get-account-list")]
        public async Task<IActionResult> GetUserList([FromBody]AccountFilterDto filter)
        {
            return Json(await _accountService.UserList(filter));
        }

        /// <summary>
        /// 退出登录
        /// </summary>
        [HttpGet("api/account/logout")]
        public async Task<IActionResult> LogOut()
        {
            BackJson res = new BackJson();
            await _signInManager.SignOutAsync();

            res.code = 0;
            res.msg = "退出成功";
            return Json(res);
        }
    }
}
